﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Flagwind.Data
{
	internal class LocalLoader
	{
		private AppDomain appDomain;
		private RemoteLoader remoteLoader;

		/// <summary>
		/// 根据 Flagwind.Data.dll 文件所在目录初始化加载器
		/// </summary>
		/// <param name="basePath"></param>
		public LocalLoader(string basePath)
		{
			AppDomainSetup setup = new AppDomainSetup();
			setup.ApplicationName = "Flagwind_Application";
			setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
			setup.PrivateBinPath = Path.Combine(setup.ApplicationBase, "private");
			setup.CachePath = setup.ApplicationBase;
			setup.ShadowCopyFiles = "true";
			setup.ShadowCopyDirectories = setup.ApplicationBase;
			appDomain = AppDomain.CreateDomain("Flagwind_Domain", null, setup);
			string fileName = Path.Combine(basePath, "Flagwind.Data.dll");
			//例如： @"E:\SimpleAccess\bin\Debug\Flagwind.Data.dll",
			remoteLoader = (RemoteLoader)appDomain.CreateInstanceFromAndUnwrap(fileName, typeof(RemoteLoader).FullName);
		}

		public void LoadAssembly(string fullName)
		{
			remoteLoader.LoadAssembly(fullName);
		}

		public void Unload()
		{
			AppDomain.Unload(appDomain);
			appDomain = null;
		}

		public string FullName
		{
			get
			{
				return remoteLoader.FullName;
			}
		}

		public string[] GetAllTypeNames
		{
			get
			{
				return remoteLoader.GetAllTypeNames();
			}
		}

		public string ErrorMessage
		{
			get
			{
				return remoteLoader.ErrorMessage;
			}
		}

		public object Invoke(string fullClassName, string methodName, object[] paraValues)
		{
			return remoteLoader.Invoke(fullClassName, methodName, paraValues);
		}

		public List<KeyValuePair<string, string>> GetAllPropertyNames(string className)
		{
			return remoteLoader.GetAllPropertyNames(className);
		}

		public string[] TableFieldName(string fullClassName, string propertyName)
		{
			return remoteLoader.TableFieldName(fullClassName, propertyName);
		}

		public bool IsEntityClass
		{
			get
			{
				return remoteLoader.IsEntityClass;
			}
		}
	}
}